/**
 * Alipay.com Inc.
 * Copyright (c) 2009-2010 All Rights Reserved.
 */
package com.alipay.test.dbtest.script;

import java.util.List;

/**
 * MultiScriptExecuter holds multi script executer.
 * 
 * @author quickpoint
 * @version $Id: MultiScriptExecuter.java, v 0.1 2010-5-29 下午08:47:05 quickpoint Exp $
 */
public class MultiScriptExecuter implements ScriptExecuter {

    /**
     * multi script executers
     */
    private List<ScriptExecuter> executers;

    /**
     * should stop execute when exception happens. true--stop, false--not stop
     */
    private boolean              shouldStopWhenEx = false;

    /* (non-Javadoc)
     * @see com.alipay.test.dbtest.script.ScriptExecuter#execute(java.lang.String)
     */
    public void execute(String line) throws ScriptException {
        if (shouldStopWhenEx) {
            executeStopWhenEx(line);
        } else {
            executeNoStopWhenEx(line);
        }
    }

    /**
     * 
     * @param line
     * @throws ScriptException
     */
    private void executeNoStopWhenEx(String line) throws ScriptException {
        boolean existsEx = false;
        ScriptException lastEx = null;
        for (ScriptExecuter each : executers) {
            try {
                each.execute(line);
            } catch (ScriptException ex) {
                existsEx = true;
                lastEx = ex;
                continue;
            }
        }
        if (existsEx) {
            throw new ScriptException("exception happened, last exception:", lastEx);
        }
    }

    private void executeStopWhenEx(String line) throws ScriptException {
        for (ScriptExecuter each : executers) {
            each.execute(line);
        }
    }

    /**
     * @param executers The executers to set.
     */
    public void setExecuters(List<ScriptExecuter> executers) {
        this.executers = executers;
    }

    /**
     * @param shouldStopWhenEx The shouldStopWhenEx to set.
     */
    public void setShouldStopWhenEx(boolean shouldStopWhenEx) {
        this.shouldStopWhenEx = shouldStopWhenEx;
    }
}
